<?php

use think\Db;

/*
 * 查询表格数据
 * tableName 	表名，不用写前缀
 * where 		条件，数组格式
 * order 		排序，字符串
 */
function select_table_data($tableName,$where=null,$order=null) {
	$param = get_table_param($where,$order);
	$getData = Db::name($tableName) -> where($param['where']) -> order($param['order']) -> page($param['page'], $param['limit']) -> select();
	$getDataCount = Db::name($tableName) -> where($param['where']) -> count();
	$r['data'] = $getData;
	$r['count'] = $getDataCount;
	return $r;
}

/*
 * 获取表格所需参数使用input获取
 */
function get_table_param($where=null,$order=null) {
	//排序：id desc	,如果方法参数存在$order,会被覆盖此参数
	$r['order'] = input('param.order');
	$r['where']='';
	if($r['order']==''){
		$r['order'] = $order;
	}
	
	//条件：https://www.kancloud.cn/manual/thinkphp5/118073，数组查询
	//,如果方法参数存在$where,会被覆盖此参数
	if(!empty($_POST['where'])){
		$r['where'] = $_POST['where'];
		if(is_array($r['where'])){
			$r['where'] = disposeWhere($r['where']);
		}
	}
	
	
	if($where){
		//待验证...
		if($r['where']==''){
			$r['where'] = $where;
		}else{
			$r['where'] = array_merge($r['where'],$where);
		}
		
	}
	//分页：默认(1,30)
	$r['page'] = input('param.page') ? input('param.page') : 1;
	$r['limit'] = input('param.limit') ? input('param.limit') : 30;
	return $r;
}

//处理where
function disposeWhere($w){
	$newWhereArr=array();
	foreach ($w as $k => $v) {
		if(isset($v['exp'])){
			switch ($v['exp']) {
				case 'like':
					$newWhereArr[$v['field']]=array('like',"%{$v['value']}%");
					break;
					
				case 'eq':
					$newWhereArr[$v['field']]=array('eq',$v['value']);
					break;
					
				case 'neq':
					$newWhereArr[$v['field']]=array('neq',$v['value']);
					break;
					
				default:
					
					break;
			}
		}elseif(isset($v['type'])){
			switch ($v['type']) {
				case 'between':
					$newWhereArr[$v['field']]=array('between',array($v['valueStart'],$v['valueEnd']));
					break;
				case 'time':
					$startTime=strtotime($v['valueStart']);
					$endTime=strtotime($v['valueEnd']);
					$newWhereArr[$v['field']]=array('between',array($startTime,$endTime));
					break;
				
				default:
					$newWhereArr[$v['field']]=array('eq',$v['value']);
					break;
			}
			
		}else{
			
			$newWhereArr[$v['field']]=array('eq',$v['value']);
		}
	}
	return $newWhereArr;
}
